<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="父经销商" prop="parentId">
          <el-select v-model="queryParams.parentId" placeholder="请选择经父经销商"  clearable
            @keyup.enter.native="handleQuery">
              <el-option v-for="(item, index) in parentIdOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="经销商名称" prop="dealerName">
          <el-input
            v-model="queryParams.dealerName"
            placeholder="请输入经销商名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input
            v-model="queryParams.leader"
            placeholder="请输入负责人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入联系电话"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="证件号" prop="idNum">
          <el-input
            v-model="queryParams.idNum"
            placeholder="请输入证件号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="queryParams.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input
            v-model="queryParams.province"
            placeholder="请输入省份"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input
            v-model="queryParams.city"
            placeholder="请输入市"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="区" prop="district">
          <el-input
            v-model="queryParams.district"
            placeholder="请输入区"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="经销商级别" prop="dealerLevel">
          <el-select v-model="queryParams.dealerLevel" placeholder="请选择经销商级别"  clearable
            @keyup.enter.native="handleQuery">
              <el-option v-for="(item, index) in dealerLevelOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:dealer:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:dealer:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:dealer:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:dealer:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="dealerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="父经销商" align="center" prop="parentDealerName" />
        <el-table-column label="经销商名称" align="center" prop="dealerName" />
        <el-table-column label="显示顺序" align="center" prop="orderNum" />
        <el-table-column label="负责人" align="center" prop="leader" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <el-table-column label="证件类型" align="center" prop="idTypeName" />
        <el-table-column label="证件号" align="center" prop="idNum" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="省份" align="center" prop="province" />
        <el-table-column label="市" align="center" prop="city" />
        <el-table-column label="区" align="center" prop="district" />
        <el-table-column label="经销商级别" align="center" prop="dealerLevelName" />
        <el-table-column label="状态" align="center" prop="statusName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dealer:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:dealer:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改经销商对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="父经销商" prop="parentId">
            <el-select v-model="form.parentId" placeholder="请选择父经销商" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in parentIdOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="经销商名称" prop="dealerName">
            <el-input v-model="form.dealerName" placeholder="请输入经销商名称" :maxlength="50" show-word-limit
              clearable :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="fileId" required>
              <el-upload ref="headPic" :on-exceed="headPicexceed" :limit="1" list-type="picture-card" :on-remove="handleHeadPicRemove" :before-upload="headPicBeforeUpload" :on-success="uploadHeadPic" :file-list="headPicList" action="https://meiyang.zoorank.com/dev-file/upload">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input-number v-model="form.orderNum" placeholder="显示顺序" controls-position=right>
            </el-input-number>
          </el-form-item>
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="form.leader" placeholder="请输入负责人" :maxlength="50" show-word-limit clearable
              :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" show-word-limit clearable
              :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="证件类型" prop="idType">
            <el-select v-model="form.idType" placeholder="请选择证件类型" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in idTypeOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号" prop="idNum">
            <el-input v-model="form.idNum" placeholder="请输入证件号" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" clearable :style="{width: '100%'}">
            </el-input>
            </el-form-item>
            <el-form-item label="省份" prop="province">
            <el-input v-model="form.province" placeholder="请输入省份" :maxlength="50" show-word-limit clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="市" prop="city">
            <el-input v-model="form.city" placeholder="请输入市" :maxlength="50" show-word-limit clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="区" prop="district">
            <el-input v-model="form.district" placeholder="请输入区" :maxlength="50" show-word-limit clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
          <el-form-item label="经销商级别" prop="dealerLevel">
            <el-select v-model="form.dealerLevel" placeholder="请选择经销商级别" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in dealerLevelOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status" size="small">
                <el-radio-button v-for="(item, index) in statusOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listDealer, getDealer, delDealer, addDealer, updateDealer } from "@/api/system/dealer";
  
  export default {
    name: "Dealer",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 经销商表格数据
        dealerList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          parentId: null,
          ancestors: null,
          dealerName: null,
          orderNum: null,
          leader: null,
          phone: null,
          idType: null,
          idNum: null,
          email: null,
          province: null,
          city: null,
          district: null,
          longitude: null,
          latitude: null,
          dealerLevel: null,
          status: null,
        },
        queryDealerSelectParams: {
          pageNum: 1,
          pageSize: 1000
        },
        // 表单参数
        form: {
          parentId: undefined,
          dealerName: undefined,
          orderNum: 0,
          leader: undefined,
          ancestors: undefined,
          phone: '',
          idNum: undefined,
          idType: 0,
          dealerLevel: undefined,
          email: undefined,
          province: undefined,
          city: undefined,
          district: undefined,
          longitude: undefined,
          latitude: undefined,
          status: 0,
        },
        headPicList:[],
        // 表单校验
        rules: {
          dealerName: [{
            required: true,
            message: '请输入经销商名称',
            trigger: 'blur'
          }],
          orderNum: [{
            required: true,
            message: '显示顺序',
            trigger: 'blur'
          }],
          leader: [{
            required: true,
            message: '请输入负责人',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          }, {
            pattern: /^1(3|4|5|7|8|9)\d{9}$/,
            message: '请输入正确的联系电话',
            trigger: 'blur'
          }],
          idType: [{
            required: true,
            message: '请选择证件类型',
            trigger: 'change'
          }],
          idNum: [{
            required: true,
            message: '请输入证件号',
            trigger: 'blur'
          }],
          dealerLevel: [{
            required: true,
            message: '请选择经销商级别',
            trigger: 'change'
          }],
          email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }, {
          pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
          message: '请输入正确的邮箱',
          trigger: 'blur'
        }],
        province: [{
          required: true,
          message: '请输入省份',
          trigger: 'blur'
        }],
        city: [{
          required: true,
          message: '请输入市',
          trigger: 'blur'
        }],
        district: [{
          required: true,
          message: '请输入区',
          trigger: 'blur'
        }],
        longitude: [{
          required: true,
          message: '经度',
          trigger: 'blur'
        }],
        latitude: [{
          required: true,
          message: '纬度',
          trigger: 'blur'
        }],
        status: [{
          required: true,
          message: '状态不能为空',
          trigger: 'change'
        }],
        },
        parentIdOptions: [],
        dealerLevelOptions: [{
          "label": "省",
          "value": '1'
        }, {
          "label": "市",
          "value": '2'
        }, {
          "label": "区",
          "value": '3'
        }],
        idTypeOptions: [{
          "label": "身份证",
          "value": '0'
        }, {
          "label": "其他",
          "value": '1'
        }],
        statusOptions: [{
          "label": "正常",
          "value": 0
        }, {
          "label": "停用",
          "value": 1
        }],
      };
    },
    created() {
      this.getList();
      this.getDealerSelect();
    },
    methods: {
      getDealerSelect() {
            listDealer(this.queryDealerSelectParams).then(response => {
                let dealerList = response.rows;
                if(dealerList){
                    let arr = []
                    dealerList.forEach(element => {
                        arr.push({"label": element.dealerName,"value": element.id})
                    });
                    this.parentIdOptions = arr
                }
            });
        },
      /** 查询经销商列表 */
      getList() {
        this.loading = true;
        listDealer(this.queryParams).then(response => {
          this.dealerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          parentId: null,
          ancestors: null,
          dealerName: null,
          orderNum: null,
          leader: null,
          phone: null,
          idType: null,
          idNum: null,
          email: null,
          province: null,
          city: null,
          district: null,
          longitude: null,
          latitude: null,
          dealerLevel: null,
          status: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          fileId: null
        };
        this.headPicList = []
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加经销商";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getDealer(id).then(response => {
          this.form = response.data;
          if(this.form.fileId){
            this.headPicList= [{name:this.form.fileName,url:this.form.fileUrl}]
          }
          this.open = true;
          this.title = "修改经销商";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateDealer(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addDealer(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除经销商编号为"' + ids + '"的数据项？').then(function() {
          return delDealer(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/dealer/export', {
          ...this.queryParams
        }, `dealer_${new Date().getTime()}.xlsx`)
      },
      uploadHeadPic(res, file, fileList){
        this.form.fileId = res.data.fileId
      },

      handleHeadPicRemove(file, fileList){
        this.headPicList = [];
        this.form.fileId = null;
      },

      headPicBeforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize&&isJPG;
      },
      headPicexceed(files, fileList){
        this.$message.error('只能上传一个头像!');
      }
    },
  };
  </script>
  